﻿using System.Windows;
using System.Windows.Threading;

namespace CSharpAllDemo
{
    public class ExceptionManager
    {
        private static ExceptionManager _instance;

        public static ExceptionManager Instance()
        {
            if (_instance == null)
            {
                _instance = new ExceptionManager();
            }
            return _instance;
        }

        public void CatchException(Application app)
        {
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException;//Task异常

            //UI线程未捕获异常处理事件（UI主线程）
            app.DispatcherUnhandledException += UIDispatcherUnhandledException;

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
        }

        private void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            else
            {
                MessageBox.Show(e.ExceptionObject.ToString());
            }
        }

        private void TaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved();

            MessageBox.Show(e.Exception.Message);
        }

        private void UIDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            MessageBox.Show(e.Exception.Message);
        }
    }
}